package kr.saeildamil.androidStudy_second.multimedia;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.ArrayList;

import kr.saeildamil.androidStudy_second.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class PlayAudio extends Activity {
	ArrayList<String> mList;
	int mIdx;
	MediaPlayer mPlayer;
	Button mPlayBtn;
	TextView mFileName;
	SeekBar mProgress;
	boolean wasPlaying;
	String mSdPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch33_playaudio);

		mList = new ArrayList<String>();
		mPlayer = new MediaPlayer();

		String ext = Environment.getExternalStorageState();
		if (!ext.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
			Toast.makeText(this, "SD카드가 필요합니다.", Toast.LENGTH_LONG).show();
			finish();
			return;
		}

		mSdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		File sdRoot = new File(mSdPath);
		FilenameFilter filter = new FilenameFilter() {
			public boolean accept(File dir, String filename) {
				return filename.endsWith(".mp3");
			}
		};

		String[] mpList = sdRoot.list(filter);
		if (mpList.length == 0) {
			Toast.makeText(this, "재생가능 파일이 없음", Toast.LENGTH_LONG).show();
			finish();
			return;
		}

		for (String str : mpList) {
			mList.add(mSdPath + "/" + str);
			// Toast.makeText(this, str, Toast.LENGTH_LONG).show();
		}
		mIdx = 0;

		mFileName = (TextView) findViewById(R.id.filename);
		mPlayBtn = (Button) findViewById(R.id.play);
		mProgress = (SeekBar) findViewById(R.id.progress);

		mPlayer.setOnCompletionListener(mOnComplete);
		mPlayer.setOnSeekCompleteListener(mOnSeekComplete);

		mProgress.setOnSeekBarChangeListener(mOnSeek);
		mProgressHandler.sendEmptyMessageDelayed(0, 200);

		if (!loadMedia(mIdx)) {
			Toast.makeText(this, "파일을 읽을수 없음", Toast.LENGTH_LONG).show();
			finish();
		}
	}

	public void mOnclick(View v) {
		switch (v.getId()) {
		case R.id.play:
			if (mPlayer.isPlaying() == false) {
				mPlayer.start();
				mPlayBtn.setText("Pause");
			} else {
				mPlayer.pause();
				mPlayBtn.setText("Play");
			}
			break;
		case R.id.stop:
			mPlayer.stop();
			mPlayBtn.setText("Play");
			mProgress.setProgress(0);
			Prepare();
			break;
		case R.id.prev:
		case R.id.next:
			boolean wasPlaying = mPlayer.isPlaying();
			if (v.getId() == R.id.prev) {
				mIdx = (mIdx == 0 ? mList.size() - 1 : mIdx - 1);
			} else {
				mIdx = (mIdx == mList.size() - 1 ? 0 : mIdx - 1);
			}
			mPlayer.reset();
			loadMedia(mIdx);

			if (wasPlaying) {
				mPlayer.start();
				mPlayBtn.setText("Pause");
			}
			break;
		}
	}

	boolean Prepare() {
		try {
			mPlayer.prepare();
		} catch (IllegalStateException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	protected void onPause() {
		super.onPause();
		if (mPlayer != null) {
			mPlayer.release();
			mPlayer = null;
		}
	};

	MediaPlayer.OnErrorListener mOnError = new OnErrorListener() {
		public boolean onError(MediaPlayer mp, int what, int extra) {
			String err = "OnError occured. what = " + what + ", extra = "
					+ extra;
			Toast.makeText(PlayAudio.this, err, Toast.LENGTH_LONG).show();
			return false;
		}
	};

	Handler mProgressHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if (mPlayer == null)
				return;
			if (mPlayer.isPlaying()) {
				mProgress.setProgress(mPlayer.getCurrentPosition());
			}
			mProgressHandler.sendEmptyMessageDelayed(0, 200);
		};
	};

	OnSeekBarChangeListener mOnSeek = new OnSeekBarChangeListener() {
		public void onStopTrackingTouch(SeekBar seekBar) {

		}

		public void onStartTrackingTouch(SeekBar seekBar) {
			wasPlaying = mPlayer.isPlaying();
			if (wasPlaying) {
				mPlayer.pause();
			}
		}

		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser) {
				mPlayer.seekTo(progress);
			}
		}
	};

	OnSeekCompleteListener mOnSeekComplete = new OnSeekCompleteListener() {
		public void onSeekComplete(MediaPlayer mp) {
			if (wasPlaying) {
				mPlayer.start();
			}
		}
	};

	OnCompletionListener mOnComplete = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mp) {
			mIdx = (mIdx == mList.size() - 1 ? 0 : mIdx + 1);
			mPlayer.reset();// 곡이 바귀므로 reset 호출
			loadMedia(mIdx);
			mPlayer.start();
		}
	};

	boolean loadMedia(int mIdx) {
		try {
			mPlayer.setDataSource(mList.get(mIdx));
			mPlayer.prepare();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		mFileName.setText("파일 : " + mList.get(mIdx));
		mProgress.setMax(mPlayer.getDuration());
		return true;
	}
}
